package com.zmn.oms.admin.controller;

import com.zmn.common.constant.StatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局控制器异常处理器；处理控制器抛出的未处理异常，包含全局异常处理、公用异常处理。
 * <p>
 * <p>
 * 异常处理顺序：
 * 1. 响应内容类型非空：若为JSON则返回JSON错误，否则返回ERROR PAGE
 * 2. 请求内容类型非空：若为JSON则返回JSON错误，否则返回ERROR PAGE
 * 3. 返回ERROR PAGE
 * </p>
 *
 * @author duanzuocai
 * @version v1.0
 * @类说明：异常返回格式统一管理
 * @since 2018/10/25 14:26
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public static String JSON = "application/json";
    public static String JSONP = "application/jsonp";

    @Value("${web.error.page:json}")
    private String webErrorJson = "json";

    @ExceptionHandler(OmsBaseException.class)
    @ResponseBody
    public ResultDTO omsErrorHandler(OmsBaseException e) {
        logger.debug(e.getMessage(), e);
        return ResultDTO.fail(e.getMessage());
    }

    /**
     * 全局异常处理
     *
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultDTO errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            if (bindingResult.hasErrors() && bindingResult.hasFieldErrors()) {
                FieldError fieldError = bindingResult.getFieldError();
                return ResultDTO.fail(StatusConsts.ERROR_PARAMS, fieldError.getDefaultMessage());
            }
        }

        if (e instanceof MaxUploadSizeExceededException) {
            return ResultDTO.fail(StatusConsts.STATUS_ERROR, "上传文件最大5M");
        }

        logger.error(e.getMessage(), e);
        return ResultDTO.fail(e.getMessage());
    }

}